package edu.sdibt.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import edu.sdibt.bean.Custemer;

/**
 * Servlet implementation class BookBuyServlet
 */
@WebServlet("/bookBuyServlet")
public class BookBuyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BookBuyServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	    String methoed=request.getParameter("m");
	    switch (methoed) {
		case "getbookname":
            getBookName(request,response);			
 			break;

		case "getcustomermsg":
			getCustomerMsg(request,response);
			break;
		}
	}
	private void getCustomerMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		String name=request.getParameter("CusName");
		String address=request.getParameter("address");
		String caedType=request.getParameter("caedType");
		String cardNumber=request.getParameter("cardNumber");
		String telNumber=request.getParameter("telNumber");
		Custemer custemer=new Custemer(name, address, caedType, cardNumber	, telNumber);
		HttpSession session=request.getSession();
		session.setAttribute("custemer", custemer);
		response.sendRedirect(request.getContextPath()+"/BuyBooks/step3.jsp");
	}
	private void getBookName(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		// TODO Auto-generated method stub
		String[] booksName=request.getParameterValues("bookName");
		List<String> list=new ArrayList<>();
		if(booksName!=null&&booksName.length>0) {
			for(String s:booksName) {
                if(s.equals("Java")||s.equals("Oracle")||s.equals("Struts")||s.equals("JavaWeb")) {
                	list.add(s);
                }
			}
		}
		if(list!=null&&list.size()>0) {
			request.getSession().setAttribute("booksName", list);
			response.sendRedirect(request.getContextPath()+"/BuyBooks/step2.jsp");
		}else{
			request.setAttribute("errorMessage", "请先选好需要的书的再点击购买！");
			request.getRequestDispatcher("/BuyBooks/step1.jsp").forward(request, response);
		}
	}
    
}
